package concurrency;

import java.util.concurrent.TimeUnit;

class Teller implements Runnable, Comparable<Teller> {
    private static int sCounter = 0;
    
    private final int mId = sCounter++;
    
    private CustomerLine mCustomers;
    
    /**
     * Customers served during this shift
     */
    private int mCustomersServedNumber = 0;
    
    private boolean mServingCustomerLine = true;
    
    public Teller(CustomerLine customers) {
        mCustomers = customers;
    }
    
    public synchronized void doSomethingElse() {
        mCustomersServedNumber = 0;
        mServingCustomerLine = false;
    }

    public synchronized void serveCustomerLine() {
        assert !mServingCustomerLine : "already serving: " + this;
        mServingCustomerLine = true;
        notifyAll();
    }

    @Override
    public synchronized int compareTo(Teller other) {
        if (mCustomersServedNumber < other.mCustomersServedNumber) {
            return -1;
        } else if (mCustomersServedNumber == other.mCustomersServedNumber) {
            return 0;
        } else {
            return 1;
        }
    }
    
    @Override
    public void run() {
        try {
            while (!Thread.interrupted()) {
                Customer customer = mCustomers.take();
                TimeUnit.MILLISECONDS.sleep(customer.getServiceTime());
                synchronized(this) {
                    mCustomersServedNumber++;
                    // 
                    while(!mServingCustomerLine) {
                         wait();
                    }                       
                }
            }
        } catch (InterruptedException e) {
            System.out.println(this + "interrupted");
            // e.printStackTrace();
        }
    }
    
    @Override
    public String toString() {
        return "Teller " + mId + " ";
    }

    public String shortString() {
        return "T" + mId;
    }
}
